package com.BlackMesa.controllers;

/**
 * A controller for the login screen
 * 
 * @version 1.1
 * @author Nick Incardone, Tyler Bishop
 */
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.BlackMesa.database.DatabaseAdapter;
import com.BlackMesa.models.*;
import java.util.*;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class LoginViewController implements OnClickListener {
	private ArrayList<User> users;
	private Activity activity;
	public Dialog newUserDialog;
	private Button loginButton, createUserButton, cancelButton;
	private TextView createUserPopButton;
	private boolean isShowingCreate = false;
	private DatabaseAdapter adapter;

	/**
	 * creates a new login view controller and instantiates a userAdapter for
	 * persistence
	 * 
	 * @param users
	 *            an arrayList of users to check for when logging in
	 * @param activity
	 *            the current activity
	 */
	public LoginViewController(Activity activity, DatabaseAdapter adapter) {
		this.activity = activity;
		this.adapter = adapter;
		this.users = this.adapter.getUsers();
		// for (User u : users) {
		// u.setCategories(adapter.getCategories(u.getId()));
		// }
	}

	/**
	 * Initializes the buttons on the login screen and sets their listener.
	 */
	public void init() {
		loginButton = (Button) activity.findViewById(R.id.loginButton);
		createUserPopButton = (TextView) activity
				.findViewById(R.id.createUserPopButton);
		loginButton.setOnClickListener(this);
		createUserPopButton.setOnClickListener(this);
	}

	/**
	 * checks the username and password with the built in user array list
	 * 
	 * @param inputUser
	 *            the inputted username
	 * @param inputPass
	 *            the inputted password
	 */
	public void checkUsernameAndPass(String inputUser, String inputPass) {
		User currUser = new User();// Creates dud user
		for (User user : users) {
			if (inputUser.equals(user.getUsername())) {
				currUser = user;
				continue;
			}
		}
		if (currUser.getUsername() != null) {
			if (currUser.checkPass(inputPass)) {
				activity.setContentView(R.layout.list_view);
				currUser.setAdapter(adapter);
				currUser.setCategories(adapter.getCategories(currUser.getId()));
//				for (User u : users) {
//					u.setCategories(adapter.getCategories(u.getId()));
//				}
				Log.d("current user id", Integer.toString(currUser.getId()));
				ListViewController lvc = new ListViewController(currUser,
						activity, adapter);
				lvc.init();
			} else {
				alertBox("Failure", "Failed Login");
			}
		} else {
			alertBox("Failure", "Failed Login");
		}
	}

	/**
	 * creates an alert box and sets it focus to current
	 * 
	 * @param title
	 *            the header of the alertbox
	 * @param mymessage
	 *            the message displayed in the alertbox
	 */
	public void alertBox(String title, String mymessage) {
		new AlertDialog.Builder(this.activity)
				.setMessage(mymessage)
				.setTitle(title)
				.setCancelable(true)
				.setNeutralButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
							}
						}).show();
	}

	/**
	 * instantiates the new user dialog screen
	 */
	private void newUserDialog() {
		Dialog dialog = new Dialog(activity);
		dialog.setContentView(R.layout.new_user);
		dialog.setTitle("Create New User");
		dialog.show();
		this.newUserDialog = dialog;
		createUserButton = (Button) dialog.findViewById(R.id.createUser);
		cancelButton = (Button) dialog.findViewById(R.id.cancelUser);
		createUserButton.setOnClickListener(this);
		cancelButton.setOnClickListener(this);
	}

	/**
	 * creates a new user
	 * 
	 * @param name
	 * @param user
	 * @param email
	 * @param pass
	 */
	private void newUser(String name, String user, String email, String pass) {
		checkInfo(new User(name, user, email, pass, adapter));
	}

	/**
	 * Checks the info entered against current users; doesn't allow repeat
	 * usernames or emails.
	 * 
	 * @param new user being created
	 */
	private void checkInfo(User newUser) {
		if (!newUser
				.getEmail()
				.matches(
						"[a-zA-Z0-9]+[a-zA-Z0-9\\.\\_\\%\\+\\-]*@[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-]*\\.[a-zA-Z]{2,4}")) {
			alertBox("Create Failed", "Not a valid email address");
			return;
		}
		for (User u : users) {
			if (newUser.getUsername().equals(u.getUsername())
					|| newUser.getEmail().equals(u.getEmail())) {
				alertBox("Create Failed",
						"User with that email or username already exists.");
				return;
			}
		}
		adapter.createUser(newUser);
		users = adapter.getUsers();
		newUserDialog.dismiss();
		isShowingCreate = false;
	}

	/**
	 * handles clicks in the main activity @ param view the view that is
	 * currently in focus
	 */
	public void onClick(View view) {
		if (view.equals(loginButton)) {
			checkUsernameAndPass(
					((EditText) activity.findViewById(R.id.UserName)).getText()
							.toString(),
					((EditText) activity.findViewById(R.id.Password)).getText()
							.toString());
		}

		if (view.equals(createUserPopButton)) {
			newUserDialog();
			isShowingCreate = true;
		}

		if (isShowingCreate) {
			if (view.equals(createUserButton)) {

				newUser(((EditText) newUserDialog.findViewById(R.id.name))
						.getText().toString(),
						((EditText) newUserDialog.findViewById(R.id.user))
								.getText().toString(),
						((EditText) newUserDialog.findViewById(R.id.email))
								.getText().toString(),
						((EditText) newUserDialog.findViewById(R.id.pass))
								.getText().toString());
			}

			if (view.equals(cancelButton)) {
				newUserDialog.dismiss();
				isShowingCreate = false;
			}
		}

	}

}
